package com.aaa.qy127.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录过滤，除了登录页面，其他页面都不能，直接访问，如果访问，直接重定向到login.jsp
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强转一波
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        String uri = req.getRequestURI();
        int i = uri.lastIndexOf("/");
        String s = uri.substring(i + 1);
        if (s.equals("login.jsp") || s.equals("login") || uri.contains("layui") || s.equals("timg.jpg") /*|| s.equals("khdlogin.jsp") || s.equals("kehuduan.jsp")*/){
            //放行
            filterChain.doFilter(req,resp);
        }else {
            HttpSession session = req.getSession();
            /*Object staff = session.getAttribute("staff");*/
            Object staff = session.getAttribute("staff");
            if (staff!=null){
                filterChain.doFilter(req,resp);
            }else {
                resp.sendRedirect(req.getContextPath()+"/login.jsp");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
